package com.hujia.handler;

import java.util.List;

import com.hujia.entity.City;
import com.hujia.entity.Province;
import com.hujia.service.ProvinceService;

import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.ext.web.RoutingContext;

public class ProvinceHandler {
	
	private ProvinceService provinceService = new ProvinceService();
	
	public void list(RoutingContext routingContext) {
		HttpServerResponse  w = routingContext.response();
		
		
		Future<List<Province>> future = provinceService.list();
		future.setHandler(rs -> {
			if (rs.succeeded()) {
				List<Province> provinces = rs.result();
				w.putHeader("content-type", "application/json");
				w.end(Json.encode(provinces));
				return;
			}
			w.setStatusCode(500);
			w.end(rs.cause().getMessage());
		});
		
	}
	
	/**
	 * 获取某一个省份下的城市
	 */
	public void children(RoutingContext routingContext) {
		
		HttpServerResponse w = routingContext.response();
		
		String provinceCode = routingContext.request().getParam("code");
		if (provinceCode == null || provinceCode.equals("")) {
			w.setStatusCode(400);
			w.setStatusMessage("省份编号不能为空.");
			w.end();
			return;
		}
		
		Future<List<City>> future = provinceService.children(provinceCode);
		future.setHandler( rs -> {
			if (rs.succeeded()) {
				List<City> citys = rs.result();
				w.putHeader("content-type", "application/json");
				w.end(Json.encode(citys));
				return;
			}
			
			w.setStatusCode(500);
			w.end(rs.cause().getMessage());
		});
		
		return;
	}
}
